package com.rzn.reading;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult<?> handleValidationException(MethodArgumentNotValidException e) {
        return new JsonResult<>(parseFieldErrors(e.getBindingResult().getFieldErrors()));
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult<?> handleValidationException(BindException e) {
        return new JsonResult<>(parseFieldErrors(e.getBindingResult().getFieldErrors()));
    }

    private List<Map<String, String>> parseFieldErrors(List<FieldError> fieldErrors) {
        List<Map<String, String>> errorList = null;
        if (fieldErrors != null && fieldErrors.size() > 0) {
            errorList = fieldErrors.stream().map(e -> {
                Map<String, String> tmp = new HashMap<>();
                tmp.put("field", e.getField());
//                tmp.put("code", e.getCode());
                tmp.put("code", "500");
                tmp.put("message", e.getDefaultMessage());
                return tmp;
            }).collect(Collectors.toList());
        }
        return errorList;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult<?> handleBusinessException(BusinessException e) {
        JsonResult<?> result = new JsonResult<>();
        result.setMessage(e.getMessage());
        result.setCode(400);
        return result;
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public JsonResult<?> handleAccessDeniedException(AccessDeniedException e) {
        JsonResult<?> result = new JsonResult<>();
        result.setMessage("该角色无权访问");
        return result;
    }

    /**
     * 参数校验异常处理
     *
     * @param e 捕获的异常
     * @return 异常处理结果
     * @Author 86176
     * @Create 2022/1/17 14:30
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult<?> handleConstraintViolationException(ConstraintViolationException e) {
        return JsonResult.error(e.getMessage());
    }
}
